/*
 * rss.c
 *
 *  Created on: Feb 10, 2012
 *      Author: daniel
 */

#include "rss.h"
#include "pollerutils.h"
#include "curl/curl.h"
#include "../renderers/news.h"
#include <mxml.h>
#include <glib.h>

static char* gettext(mxml_node_t* firstnode) {

	int remaining = 1024;
	char* buffer = malloc(remaining);
	gchar* current = buffer;
	mxml_node_t* child;
	for (child = firstnode; child != NULL; child = child->next) {
		remaining -= strlen(child->value.text.string) + 1;
		if (remaining >= 1) {
			current = g_stpcpy(current, child->value.text.string);
			//for (int i = 0; i < child->value.text.whitespace; i++) {
				current = g_stpcpy(current, " ");
			//}
		}
		else {
			break;
		}
	}

	buffer = realloc(buffer, strlen(buffer) + 1);

	return buffer;
}

static void poll() {

	expandinglump_t chunk;
	pollerutils_httpget("http://feeds.bbci.co.uk/news/uk/rss.xml", &chunk);
	printf("--\n%s\n--\n", chunk.memory);

	mxml_node_t* root = mxmlLoadString(NULL, chunk.memory, MXML_TEXT_CALLBACK);

	mxml_node_t* channel = mxmlFindElement(root, root, "channel", NULL, NULL, MXML_DESCEND);

	mxml_node_t* node;

	for (node = mxmlFindElement(channel, channel, "item", NULL, NULL, MXML_DESCEND); node != NULL; node =
			mxmlFindElement(node, channel, "item", NULL, NULL, MXML_DESCEND)) {

		/*
		 <item>
		 <title>Man held after Glasgow siege ends</title>
		 <description>A man is being held after armed police stormed in to an Italian restaurant in Glasgow city centre, ending a siege that lasted nearly eight hours.</description>
		 <link>http://www.bbc.co.uk/go/rss/int/news/-/news/uk-scotland-glasgow-west-16991511</link>
		 <guid isPermaLink="false">http://www.bbc.co.uk/news/uk-scotland-glasgow-west-16991511</guid>
		 <pubDate>Sat, 11 Feb 2012 00:50:00 GMT</pubDate>
		 <media:thumbnail width="66" height="49" url="http://news.bbcimg.co.uk/media/images/58440000/jpg/_58440855_restaurant.jpg"/>
		 <media:thumbnail width="144" height="81" url="http://news.bbcimg.co.uk/media/images/58443000/jpg/_58443282_restaurant.jpg"/>
		 </item>
		 */

		mxml_node_t* title = mxmlFindElement(node, node, "title", NULL, NULL, MXML_DESCEND);
		mxml_node_t* description = mxmlFindElement(node, node, "description", NULL, NULL, MXML_DESCEND);

		newsitem_t* item = malloc(sizeof(item));
		item->title = gettext(title->child);
		item->body = gettext(description->child);

		printf("title\n%s\n", item->title);
		printf("desc\n%s\n", item->body);

		free(item->body);
		free(item->title);
		free(item);

	}

	mxmlDelete(root);
	free(chunk.memory);

}

poller_t rsspoller = { NULL, NULL, NULL, poll, NULL };
